package icu.d4peng.basic.captcha.service.impl;

import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import icu.d4peng.basic.captcha.properties.CaptchaProperties;
import icu.d4peng.basic.captcha.service.CaptchaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * CaptchaServiceImpl:验证码服务实现
 *
 * @author d4peng <a href="d4peng@qq.com">d4peng@qq.com</a>
 * @since 2023.12.02
 */
public class CaptchaServiceImpl implements CaptchaService {

	private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaServiceImpl.class);

	private final CaptchaProperties captchaProperties;

	private Captcha captcha = null;

	public CaptchaServiceImpl(CaptchaProperties captchaProperties) {
		this.captchaProperties = captchaProperties;
		Assert.notNull(captchaProperties, "captcha properties not null!");
	}

	@Override
	public void create() {
		switch (this.captchaProperties.getType()) {
			case ARITHMETIC:
				this.captcha = new ArithmeticCaptcha();
				break;
			case CHINESE:
				this.captcha = new ChineseCaptcha();
				break;
			case CHINESE_GIF:
				this.captcha = new ChineseGifCaptcha();
				break;
			case GIF:
				this.captcha = new GifCaptcha();
				break;
			case SPEC:
				this.captcha = new SpecCaptcha();
				break;
			default:
				// throw new CaptchaException(CaptchaException.NO_TYPE);
		}
		try {
			this.captcha.setFont(captchaProperties.getFontType());
		}
		catch (Exception e) {
			LOGGER.error(e.getMessage());
			throw new RuntimeException(e);
		}
		this.captcha.setCharType(captchaProperties.getTextType());
		this.captcha.setLen(captchaProperties.getTextLength());
		this.captcha.setHeight(captchaProperties.getHeight());
		this.captcha.setWidth(captchaProperties.getWidth());
	}

	@Override
	public String toText() {
		Assert.notNull(this.captcha, "captcha can not null,please create before!");
		return this.captcha.text();
	}

	@Override
	public String toBase64() {
		Assert.notNull(this.captcha, "captcha can not null,please create before!");
		return this.captcha.toBase64();
	}

}
